<?php
/**
 * 图片上传组件
 * 参考：http://www.uploadify.com/documentation/
 * @author ycoe
 *
 */
class UploaderWidget extends YWidget{
	//图片列表
	public $pictures = null;
	
	//主图
	public $main_picture = null;
	
	//主图input的名称
	public $main_picture_name = 'main_picture';
	
	//图片表单名称
	public $default_image_name = 'pictures';
	
	//模块名称，用于结成表单
	public $name = 'pictures[]';
	
	//显示规格
	public $thumb = '80x80';
	
	//是否支持多图片
	public $mutil = true;
	
	//上传完成后执行
	public $on_upload_js = null;
	
	//默认上传完成后事件
	public $default_onload_js = null;
	
	//上传按钮背景图片
	public $upload_btn_img = '/images/add_image.png';
	
	//上传按钮的宽
	public $upload_btn_width = 43;
	
	//上传按钮的高
	public $upload_btn_height = 43;
	
	//是否有主图片
	public $has_main_picture = true;
	
	public $base_path = null;
	
	public function run(){
		$this->load_resource();
		$this->cs->registerScriptFile(BASE_URL . '/js/jquery_plus/uploadify/jquery.uploadify.min.js', CClientScript::POS_END);
		$this->cs->registerCssFile(BASE_URL . '/js/jquery_plus/uploadify/uploadify.css');
		
		if($this->default_onload_js === null){
			$this->default_onload_js = 'y_on_uploaded_' . $this->tpl;
		}
	
		$now = time();
		$token = md5(SITE_ID . $now);
		$uploadify_conf = array(
			'formData'     		=> array(
				'timestamp' 	=> $now,
				'token'     	=> $token,
			),
			'buttonImage' 		=> $this->upload_btn_img,
			'width'				=> $this->upload_btn_width,
			'height'			=> $this->upload_btn_height,
			'mutil'				=> $this->mutil ? 'true' : 'false',
			'queueID'			=> 'queue_' . $this->id . '',
			'sessionName'		=> Yii::app()->session->sessionName,
			'swf'      			=> '/js/jquery_plus/uploadify/uploadify.swf',
			'uploader' 			=> '/manage/site/upload',
			'onUploadSuccess'	=> '__ON_UPLOADED__',
		);
		
		$conf_str = json_encode($uploadify_conf);
		$param = array(
			"'{$this->id}'",
			'eval("(" + data + ")")',
			"'{$this->name}'",
			"'{$this->thumb}'",
		);
		$param_str = implode(',', $param);
		$on_loaded = $this->default_onload_js . '(' . $param_str . ');';
		if($this->on_upload_js !== null){
			$on_loaded .= $this->on_upload_js . '(' . $param_str . ');';
		}
		$conf_str = preg_replace('/"__ON_UPLOADED__"/', 'function(file, data, response){' . $on_loaded . '}', $conf_str);
		
		$this->cs->registerScript('', '$("#file_' . $this->id . '").uploadify(' . $conf_str . ');');
		$this->render($this->class_name . '/' . $this->tpl, array(
			'id' 				=> $this->id,
			'has_main_picture'	=> $this->has_main_picture,
			'pictures' 			=> $this->pictures,
			'main_picture_name' => $this->main_picture_name,
			'thumb' 			=> $this->thumb,
			'main_picture' 		=> $this->main_picture,
			'name'				=> $this->name,
			'base_path'			=> $this->base_path,
			'mutil' 			=> $this->mutil
		));
	}
}
?>